<?php
namespace Admin\Controller;

/**
 * 后台内容控制器 通用类  基于Service
 *所有的处理放在Model定义
 */
class BaseManageController extends AdminController {

	protected $modelName; // 必须定义
	protected $is_del = false; // 是否真实删除
	protected $jumpAct = ''; //设置成功操作跳转的操作
	protected $modelType = 0; // 0为service 1为model

	protected $where;
	protected $base;
	protected $sort = '';
	protected $model;
	protected $text_map = array(
		'status' => array(0 => '禁用', '1' => '开启', '-1' => '删除'),
	); // 字符和文字的映射关系

	protected function _initialize() {
		parent::_initialize();
		if (!$this->modelName) {
			$this->error('未定义模型modelName');
		}
		$this->jumpAct = $this->jumpAct ? U($this->jumpAct) : '';
		$this->model = $this->modelType == 1 ? D($this->modelName) : D($this->modelName, 'Service');
	}

	public function index() {
		$lists = $this->getList($this->modelName, $this->where, $this->sort, $this->base);
		int_to_string($lists, $this->text_map);
		$this->format_lists($lists);
		$this->_list = $lists;
		$this->display();
	}

	// 前置操作 用于做筛选
	public function _before_index() {
		$this->where = array();
	}

	public function format_lists(&$lists) {

	}

	// 添加
	public function add() {
		if (IS_POST) {
			$data = $this->model->create();
			if ($data) {
				unset($data['id']);
			}
			if ($data && $this->model->add($data)) {
				// 删除了jumpAct调用U函数  ini里已经做了
				$this->_after_add($data);
				$this->success('操作成功!', $this->jumpAct);
			} else {
				$this->error($this->model->getError());
			}
		} else {
			$this->display('form');
		}
	}

	// 编辑
	public function edit($id) {
		$id = I('id');
		$id = is_numeric($id) ? (int)$id: $id;
		$this->model->id = $this->id = $id;
		if (IS_POST) {
			$data = I('');
			$data[$this->model->getPk()] = $id;
			$data = $this->model->create($data);
			unset($data['id']);
			$map = array($this->model->getPk() => $id);
			if ($data && $this->model->where($map)->save($data)) {
				$this->_after_edit($data);
				$this->success('操作成功!', $this->jumpAct);
			} else {
				$this->error($this->model->getError());
			}
		} else {
			$data[] = $this->model->find($id);
			int_to_string($data, $this->text_map);
			$this->assign($data[0]);
			$this->display('form');
		}
	}

	public function _after_edit(&$data)
	{
		# code...
	}

	public function _after_add(&$data)
	{
		# code...
	}

	// 删除
	public function del($id) {
		$id = array_unique((array) I('id', 0));
		$pk = $this->model->getPk();
		if ($pk == '_id'){
			foreach ($id as $_id) {
				$ids[] = new \MongoId($_id);
			}
			$map[$pk] = array('in', $ids);
		}else{
			$id = is_array($id) ? array_map('intval', $id) : intval($id);
			$map[$pk] = array('in', $id);
		}
		if ($this->is_del) {
			$res = $this->model->where($map)->delete();
			$this->success('操作成功');
		} else {
			return $this->delete($this->modelName, $map);
		}
	}

	/**
	 * 对mongo数据库的自带主键进行非物理删除
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public function trash($id)
	{
		$id = array_unique((array) I('id', 0));
		$pk = $this->model->getPk();
		foreach ($id as $_id) {
			$ids[] = new \MongoId($_id);
		}
		$map[$pk] = array('in', $ids);
		$this->model->where($map)->save(['deleted_at' => NOW_TIME]);
		$this->success('操作成功');
	}

	/**
	 * 对mongo数据库的自带主键进行非物理恢复
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public function restore($id)
	{
		$id = array_unique((array) I('id', 0));
		$pk = $this->model->getPk();
		foreach ($id as $_id) {
			$ids[] = new \MongoId($_id);
		}
		$map[$pk] = array('in', $ids);
		$this->model->where($map)->save(['deleted_at' => null]);
		$this->success('操作成功');
	}


	public function changeStatus($id, $method) {
		$id = array_unique((array) I('id', 0));
		$pk = $this->model->getPk();
		if ($pk == '_id'){
			foreach ($id as $_id) {
				$ids[] = new \MongoId($_id);
			}
			$map[$pk] = array('in', $ids);
		}else{
			$id = is_array($id) ? array_map('intval', $id) : intval($id);
			$map[$pk] = array('in', $id);
		}
		switch (strtolower($method)) {
		case 'forbid':
			$this->forbid($this->modelName, $map);
			break;
		case 'resume':
			$this->resume($this->modelName, $map);
			break;
		default:
			$this->error('参数非法');
		}
	}

	protected function getList($model, $where = array(), $order = '', $base = array('status' => array('egt', 0)), $field = true) {
		$options = array();
		$REQUEST = (array) I('request.');
		if (is_string($model)) {
			$model = D($model, 'Service');
		}

		$OPT = new \ReflectionProperty($model, 'options');
		$OPT->setAccessible(true);

		$pk = $model->getPk();
		if ($order === null) {
			//order置空
		} else if (isset($REQUEST['_order']) && isset($REQUEST['_field']) && in_array(strtolower($REQUEST['_order']), array('desc', 'asc'))) {
			$options['order'] = '`' . $REQUEST['_field'] . '` ' . $REQUEST['_order'];
		} elseif ($order === '' && empty($options['order']) && !empty($pk)) {
			$options['order'] = $pk . ' desc';
		} elseif ($order) {
			$options['order'] = $order;
		}
		unset($REQUEST['_order'], $REQUEST['_field']);

		$options['where'] = array_filter(array_merge((array) $base, /*$REQUEST,*/(array) $where), function ($val) {
			if ($val === '' || $val === null) {
				return false;
			} else {
				return true;
			}
		});
		if (empty($options['where'])) {
			unset($options['where']);
		}
		$options = array_merge((array) $OPT->getValue($model), $options);
		$total = $model->where($options['where'])->count();
		if (isset($REQUEST['r'])) {
			$listRows = (int) $REQUEST['r'];
		} else {
			$listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
		}
		$page = new \Think\Page($total, $listRows, $REQUEST);
		if ($total > $listRows) {
			$page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
		}
		$p = $page->show();
		$this->assign('_page', $p ? $p : '');
		$this->assign('_total', $total);
		$options['limit'] = $page->firstRow . ',' . $page->listRows;

		$model->setProperty('options', $options);

		return $model->select();
	}

	protected function editRow($model, $data, $where, $msg) {
		// $id = array_unique((array) I('id', 0));
		// $id = is_array($id) ? array_map('intval', $id) : intval($id);
		// $where = array_merge(array('id' => array('in', $id)), (array) $where);
		// print_r($where);
		$msg = array_merge(array('success' => '操作成功！', 'error' => '操作失败！', 'url' => '', 'ajax' => IS_AJAX), (array) $msg);
		if (D($model, 'Service')->where($where)->save($data) !== false) {
			$this->_after_editRow($id, $data);
			$this->success($msg['success'], $msg['url'], $msg['ajax']);
		} else {
			$this->error($msg['error'], $msg['url'], $msg['ajax']);
		}
	}

	public function _after_editRow($id, $data)
	{
		
	}

}